package com.raos.springcloud.weather.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.raos.springcloud.weather.vo.WeatherResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/11/8 21:12
 * 天气数据服务接口实现
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {
    private static final  Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /** 天气调用远程接口 */
    private static final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = WEATHER_API + "?citykey=" + cityId;
        return this.doGetWeatherData(uri);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String uri = WEATHER_API + "?city=" + cityName;
        return this.doGetWeatherData(uri);
    }

    /**
     * 通过远程调用接口地址获取天气数据
     * @param uri 远程调用地址
     * @return 天气数据
     */
    private WeatherResponse doGetWeatherData(String uri) {
        ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
        String key = uri;
        String strBody = null;

        // 先查缓存，没有再查服务
        Boolean hasKey = this.stringRedisTemplate.hasKey(key);
        if (hasKey) {
            logger.info("存在 key={}, value={}", key ,ops.get(key));
            strBody = ops.get(key);
        } else {
            logger.info("不存在 key：{}", key);
            throw new RuntimeException("没有相应的天气信息");
        }
        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse weather = null;
        try {
            weather = mapper.readValue(strBody, WeatherResponse.class);
        } catch (IOException e) {
            logger.error("JSON反序列化异常！", e);
            throw new RuntimeException("天气信息解析失败");
        }
        return weather;
    }

}
